package olddriver.wyf.com.olddriver

import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity

import kotlinx.android.synthetic.main.activity_main.*
import olddriver.wyf.com.olddriver.fragment.SearchDetailFragment
import olddriver.wyf.com.olddriver.fragment.SearchFragment
import olddriver.wyf.com.olddriver.fragment.SearchResultFragment

class MainActivity : AppCompatActivity() {

    var searchFragment: SearchFragment = SearchFragment()
    var searchDetailFragment: SearchDetailFragment? = null
    var searchResultFragment:SearchResultFragment?=null
    var fm: FragmentManager = supportFragmentManager

    enum class FragmentEnum {
        SEARCH_FRAGMENT, SEARCH_DETAIL_FRAGMENT,SEARCH_RESULT_FRAGMENT
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setTitle("二次元Bt")
        switchFragment(FragmentEnum.SEARCH_FRAGMENT)
    }

    fun switchFragment(frag: FragmentEnum) {
        hideFragment()
        when (frag) {
            FragmentEnum.SEARCH_FRAGMENT -> {
                if (!searchFragment.isAdded) {
                    fm.beginTransaction().add(fragment_main.id, searchFragment).show(searchFragment).commit()
                } else {
                    fm.beginTransaction().show(searchFragment).commit()
                }
            }

            FragmentEnum.SEARCH_DETAIL_FRAGMENT -> {
                if (searchDetailFragment == null) {
                    searchDetailFragment = SearchDetailFragment.newInstance()
                    fm.beginTransaction().add(fragment_main.id, searchDetailFragment).show(searchDetailFragment
                    ).commit()
                } else {
                    fm.beginTransaction().show(searchDetailFragment).commit()
                }
            }
            FragmentEnum.SEARCH_RESULT_FRAGMENT->{
                if (searchResultFragment == null){
                    searchResultFragment = SearchResultFragment.newInstance()
                    fm.beginTransaction().add(fragment_main.id,searchResultFragment).show(searchResultFragment).commit()
                }else{
                    fm.beginTransaction().show(searchResultFragment).commit()
                }
            }
        }
    }

    fun hideFragment() {
        if (searchFragment != null) {
            fm.beginTransaction().hide(searchFragment).commit()
        }
        if (searchDetailFragment != null && searchDetailFragment!!.isVisible) {
            fm.beginTransaction().hide(searchDetailFragment).commit()
        }
        if(searchResultFragment!=null&&searchResultFragment!!.isVisible){
            fm.beginTransaction().hide(searchResultFragment).commit()
        }
    }
}